package com.team.recruitment_management_system.util;

import jakarta.mail.Session;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadLocalRandom;

@Component
public class MailUtils {

    @Value("${spring.mail.username}")
    private String mailSender;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * @param to    收件人邮箱
     * @param text  邮件正文
     * @param title 标题
     */
    /* 发送验证信息的邮件 */
    public void sendMail(String to, String text, String title){
        try {
            // 解决本地DNS未配置 ip->域名场景下，邮件发送太慢的问题
            System.getProperties().setProperty("mail.mime.address.usecanonicalhostname", "false");
            MimeMessage mailMessage = javaMailSender.createMimeMessage();

            // 使用MimeMessageHelper设置邮件属性和内容
            MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true);
            Session session = mailMessage.getSession();
            // 设置 日志打印控制器
            session.setDebug(true);
            //  解决本地DNS未配置 ip->域名场景下，邮件发送太慢的问题
            session.getProperties().setProperty("mail.smtp.localhost", "myComputer");

            helper.setFrom(mailSender);
            helper.setTo(to);
            helper.setSubject(title);
            helper.setText(text, false);
            javaMailSender.send(mailMessage);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    public String getCode() {
        return String.valueOf(ThreadLocalRandom.current().nextInt(100000, 1000000));
    }
}


